package hendler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"pic/cache"
	"pic/model"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	context := c.PostForm("context")
	if title == "" || context == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := model.Article{
		//Model:   gorm.Model{},
		Title:   title,
		Context: context,
	}

	err := model.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	Article_key := "add_name_" + strconv.Itoa(int(data.ID))
	var article model.Article
	model.DB.Where("id = ?", data.ID).Find(&article)
	jsonData, _ := json.Marshal(&article)
	cache.Rdb.Set(cache.Ctx, Article_key, jsonData, time.Second*30)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
}
func Del(c *gin.Context) {
	//var art model.Article
	id := c.Query("id")

	err := model.DB.Where("id = ?", id).Delete(&model.Article{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "del_id_" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}
func List(c *gin.Context) {
	var arts []model.Article
	redis_key := "redis_list"
	Data, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if Data == "" {
		model.DB.Debug().Find(&arts)
		jsonData, _ := json.Marshal(arts)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*1)

	} else {
		json.Unmarshal([]byte(Data), &arts)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": arts,
	})
}
func DataList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	var article []model.Article
	offset := (page - 1) * size
	model.DB.Offset(offset).Limit(size).Find(&article)
	//model.DB.Offset(offset).Limit(size).Find(&arts)
	var total int64
	model.DB.Model(&model.Article{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  article,
		"total": total,
	})
}
